package com.tensquare.user.controller;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.tensquare.user.pojo.Account;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ClaimsMutator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import com.tensquare.user.pojo.User;
import com.tensquare.user.service.UserService;

import entity.PageResult;
import entity.Result;
import entity.StatusCode;
import org.springframework.web.client.RestTemplate;
import util.JwtUtil;

import javax.servlet.http.HttpServletRequest;

/**
 * 控制器层
 * @author Administrator
 *
 */
@RestController
@CrossOrigin
@RequestMapping("/user")
public class UserController {

	@Autowired
	private UserService userService;
	@Autowired
	private HttpServletRequest request;		//用来获取请求头
	@Autowired
	private JwtUtil jwtUtil;
	@Autowired
	private RedisTemplate redisTemplate;

	@GetMapping("/index")
	public String index(){
		return "demo"; //当浏览器输入/index时，会返回 /templates/demo.html页面
	}
	
	/**
	 * 查询全部用户数据
	 * @return
	 */
	@RequestMapping(method= RequestMethod.GET)
	public Result findAll(){
		return new Result(true,StatusCode.OK,"查询成功",userService.findAll());
	}
	
	/**
	 * 根据用户ID查询
	 * @param id ID
	 * @return
	 */
	@RequestMapping(value="/{id}",method= RequestMethod.GET)
	public Result findById(@PathVariable String id){
		return new Result(true,StatusCode.OK,"查询成功",userService.findById(id));
	}


	/**
	 * 分页+多条件查询
	 * @param searchMap 查询条件封装
	 * @param page 页码
	 * @param size 页大小
	 * @return 分页结果
	 */
	@RequestMapping(value="/search/{page}/{size}",method=RequestMethod.POST)
	public Result findSearch(@RequestBody Map searchMap , @PathVariable int page, @PathVariable int size){
		Page<User> pageList = userService.findSearch(searchMap, page, size);
		return  new Result(true,StatusCode.OK,"查询成功",  new PageResult<User>(pageList.getTotalElements(), pageList.getContent()) );
	}

	/**
     * 根据条件查询
     * @param searchMap
     * @return
     */
    @RequestMapping(value="/search",method = RequestMethod.POST)
    public Result findSearch( @RequestBody Map searchMap){
        return new Result(true,StatusCode.OK,"查询成功",userService.findSearch(searchMap));
    }
	
	/**
	 * 增加，必须具有admin权限
	 * @param user
	 */
	@RequestMapping(method=RequestMethod.POST)
	public Result add(@RequestBody User user  ){
		//通过拦截器来判断是够是admin的角色
		/*Claims claims =(Claims) request.getAttribute("admin_claims");
		if(claims==null) return new Result(true,StatusCode.ACCESSERROR,"无权访问");*/
		String id=userService.add(user);
		return new Result(true,StatusCode.OK,"增加成功",id);
	}
	
	/**
	 * 修改用户，我可以修改我自己
	 * @param user
	 */
	@RequestMapping(method= RequestMethod.PUT)
	public Result update(@RequestBody User user ){
		//通过拦截器来判断是否是一个角色（是否登录）
		Claims admin_claims =(Claims) request.getAttribute("admin_claims");
		Claims user_claims =(Claims) request.getAttribute("user_claims");
		if(admin_claims==null&&user_claims==null) return new Result(false,StatusCode.ACCESSERROR,"无权访问");
		if(user_claims.getId().equals(user.getId()))
			userService.update(user);
		return new Result(true,StatusCode.OK,"修改成功");
	}
	//修改账户
	@RequestMapping(value="/account",method= RequestMethod.PUT)
	public Result updateAccount(@RequestBody Account account){
		//通过拦截器来判断当前登录用户和账户是否能对应上
		Claims user_claims =(Claims) request.getAttribute("user_claims");
		String uid=user_claims.getId();
		if(account.getUid().equals(uid)){
			//角色信息匹配
			userService.updateAccount(account);
			return new Result(true,StatusCode.OK,"修改成功");
		}
		else{
			return new Result(false,StatusCode.ERROR,"角色信息不匹配");
		}
	}
	
	/**
	 * 删除，必须具有admin权限
	 * @param id
	 */
	@RequestMapping(value="/{id}",method= RequestMethod.DELETE)
	public Result delete(@PathVariable String id ){
		String authHeader=request.getHeader("Authorization");
		if(authHeader==null) return new Result(false,StatusCode.ACCESSERROR,"权限不足");
		if(!authHeader.startsWith("Bearer ")) return new Result(false,StatusCode.ACCESSERROR,"权限不足");
		String token=authHeader.substring(7);		//提取token
		Claims claims = jwtUtil.parseJWT(token);
		if(claims==null) return new Result(false,StatusCode.ACCESSERROR,"权限不足");
		if(!"admin".equals(claims.get("roles"))) return new Result(false,StatusCode.ACCESSERROR,"权限不足");
		userService.deleteById(id);
		return new Result(true,StatusCode.OK,"删除成功");
	}

	/**
	 * 发送短信验证码
	 * @param mobile
	 */
	@RequestMapping(value="/sendsms/{mobile}",method=RequestMethod.POST)
	public Result sendsms(@PathVariable String mobile ){
		userService.sendSms(mobile);
		return new Result(true,StatusCode.OK,"发送成功");
	}

	/**
	 * 用户注册
	 * @param user
	 */
	@RequestMapping(value="/register/{code}",method=RequestMethod.POST)
	public Result register( @RequestBody User user ,@PathVariable String code){
		String id=userService.add(user,code);
		//注册成功返回用户的id
		return new Result(true,StatusCode.OK,"注册成功",id);
	}

	/**
	 * 用户登陆
	 * @return
	 */
	@RequestMapping(value="/login",method=RequestMethod.POST)
	public Result login(@RequestBody Map map1){
		//用户登录需要签发token，返回token，昵称，头像等信息
		User user = userService.findByMobileAndPassword((String)map1.get("mobile"),(String)map1.get("password"));
		if(user!=null){
			//把id，昵称，角色做成token
			String token = jwtUtil.createJWT(user.getId(),user.getNickname(), "user");
			Map map=new HashMap();
			map.put("id",user.getId());
			map.put("token",token);
			map.put("name",user.getNickname());//昵称
			map.put("avatar",user.getAvatar());//头像
			return new Result(true,StatusCode.OK,"登陆成功",map);
		}else{
			return new Result(false,StatusCode.LOGINERROR,"用户名或密码错误");
		}
	}

	//查询当前登录的用户信息	/user/info,需要传递header
	@RequestMapping(value = "/info",method = RequestMethod.GET)
	public Result getUserInfo(){
		Claims user_claims=(Claims)request.getAttribute("user_claims");
		//走到这说明user_claims一定不是null
		String id=user_claims.getId();
		return new Result(true,StatusCode.OK,"查询成功",userService.findById(id));
	}
	//查询当前登录用户的账户信息
	@RequestMapping(value="/account_info",method = RequestMethod.GET)
	public Result getAccount(){
		Claims user_claims=(Claims)request.getAttribute("user_claims");
		String id=user_claims.getId();
		return new Result(true,StatusCode.OK,"查询成功",userService.getAccountById(id));
	}

	//修改当前登录的用户信息	/user/saveinfo
	@RequestMapping(value = "/saveinfo",method = RequestMethod.PUT)
	public Result saveInfo(@RequestBody User user){
		//先判断出当前登录的用户是谁
		Claims user_claims=(Claims)request.getAttribute("user_claims");
		//走到这说明user_claims一定不是null
		String id=user_claims.getId();
		user.setId(id);
		userService.update(user);
		return new Result(true,StatusCode.OK,"修改成功");
	}

	//关注某用户		/user/follow/{userId}，需要判断是否已经关注过了
	@RequestMapping(value = "/follow/{userId}",method=RequestMethod.PUT)
	public Result followUser(@PathVariable("userId")String userId){
		//先得到当前登录的用户信息
		Claims user_claims=(Claims)request.getAttribute("user_claims");
		//获取当前的用户id
		String id=user_claims.getId();
		if(id.equals(userId)) return new Result(false, StatusCode.ERROR,"不能关注自己");
		//判断是否已经关注过
		if(redisTemplate.opsForValue().get("follow_"+userId)!=null){
			return new Result(false,StatusCode.OK,"您已经关注过了");
		}
		userService.followUser(id,userId);
		redisTemplate.opsForValue().set("follow_"+userId,1);
		return new Result(true,StatusCode.OK,"关注成功");
	}

	//删除对某个用户的关注	/user/follow{userId}
	@RequestMapping(value = "/follow/{userId}",method = RequestMethod.DELETE)
	public Result deleteFollow(@PathVariable String userId){
		Claims user_claims=(Claims)request.getAttribute("user_claims");
		String id=user_claims.getId();
		if(redisTemplate.opsForValue().get("follow_"+userId)==null)
			return new Result(false,StatusCode.ERROR,"未关注不能取关");
		userService.deleteFollow(id,userId);
		return new Result(true,StatusCode.OK,"取关成功");
	}

	//查询我的粉丝	/user/follow/myfans,返回一个粉丝列表，粉丝多的时候需要分页
	@RequestMapping(value = "/follow/myfans",method = RequestMethod.GET)
	public Result findMyfans(){
		Claims user_claims=(Claims)request.getAttribute("user_claims");
		String id=user_claims.getId();
		//设置分页参数，默认第一页开始，每页显示10个
		int page=1,size=10;
		Page<User> pageList=userService.findMyfans(id,page,size);
		return new Result(true,StatusCode.OK,"查询成功",
				new PageResult<User>(pageList.getTotalElements(),pageList.getContent()));
	}

	/**
	 * 增加粉丝数
	 * @param userid
	 * @param x
	 */
	@RequestMapping(value="/incfans/{userid}/{x}",method=RequestMethod.POST)
	public void incFanscount(@PathVariable String userid,@PathVariable int x){
		userService.incFanscount(userid,x);
	}
	/**
	 * 增加关注数
	 * @param userid
	 * @param x
	 */
	@RequestMapping(value="/incfollow/{userid}/{x}",method=
			RequestMethod.POST)
	public void incFollowcount(@PathVariable String userid,@PathVariable
			int x){
		userService.incFollowcount(userid,x);
	}

	//查询我的关注	/user/follow/myfollow
	@RequestMapping(value = "/follow/myfollow",method = RequestMethod.GET)
	public Result findMyfollow(){
		Claims user_claims=(Claims)request.getAttribute("user_claims");
		String id=user_claims.getId();
		int page=1,size=10;
		Page<User> pageList=userService.findMyfollow(id,page,size);
		return new Result(true,StatusCode.OK,"查询成功",
				new PageResult<User>(pageList.getTotalElements(),pageList.getContent()));
	}

	//查询我的关注id列表	/user/follow/myfollowid
	@RequestMapping(value = "/follow/myfollowid",method = RequestMethod.GET)
	public Result findMyfollowid(){
		Claims user_claims=(Claims)request.getAttribute("user_claims");
		String id=user_claims.getId();
		return new Result(true,StatusCode.OK,"查询成功",userService.findMyfollowid(id));
	}

	//设置用户头像
	@RequestMapping(value = "/setAvator",method = RequestMethod.PUT)
	public Result setAvator(@RequestBody Map map){
	    String uid=(String)map.get("uid");
	    String avatar=(String)map.get("url");
		userService.setAvator(uid,avatar);
		return new Result(true,StatusCode.OK,"设置成功");
	}
}
